package com.Nuyoah.demo01.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.Nuyoah.demo01.DTO.UserLoginDTO;
import com.Nuyoah.demo01.common.JsonResult;
import com.Nuyoah.demo01.entity.User;
import com.Nuyoah.demo01.service.CaptchaService;
import com.Nuyoah.demo01.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/users")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private CaptchaService captchaService;

    /**
     * 根据用户名获取用户信息
     *
     * @param username 用户名
     * @return 用户信息
     */
    @GetMapping("/{username}")
    public User getUserByName(@PathVariable String username) {
        return userService.getUserByName(username);
    }

    // 获取验证码
    @PostMapping("/captcha")
    public JsonResult<Map<String, String>> getCaptcha() {
//        // 假设 captchaService.generateCaptcha() 返回一个 Map<String, String>，包含 captchaImage 和 sessionId
//        Map<String, String> captchaData = captchaService.generateCaptcha();
//        if (captchaData == null || !captchaData.containsKey("captchaImage") || captchaData.get("captchaImage").isEmpty()) {
//            return new JsonResult<>("1", "验证码生成失败");
//        }
//        return new JsonResult<>("200", captchaData, "验证码生成成功");
        return captchaService.generateCaptcha();
    }

    // 注册用户
    @PostMapping("/register")
    public JsonResult registerUser(@RequestBody Map<String, Object> requestBody) {
        log.info("接收到的参数：" + requestBody);
        return userService.insertUser(requestBody);
    }

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("开始登录，接收到的参数: {}", userLoginDTO);
        return userService.login(userLoginDTO);
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/update")
    public JsonResult updateUser(@RequestParam("id") Integer id,
                                 @RequestParam("username") String username,
                                 @RequestParam("password") String password,
                                 @RequestParam("email") String email
    ) {
        log.info("开始修改用户信息，接收到的参数: id={}, username={}, password={}, email={}", id, username, password, email);
        return userService.updateUser(id,username,password,email);
    }

    /**
     * 用户退出登录
     *
     * @return 退出登录的结果
     */
    @PostMapping("/logout")
    public JsonResult<String> logout() {
        // 调用Sa-Token的logout方法销毁Token
        StpUtil.logout();
        return new JsonResult<>("200", "退出登录成功");
    }
}